{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n*origin* and *extent* in `~.Axes.imshow`\n========================================\n\n:meth:`~.Axes.imshow` allows you to render an image (either a 2D array\nwhich will be color-mapped (based on *norm* and *cmap*) or and 3D RGB(A)\narray which will be used as-is) to a rectangular region in dataspace.\nThe orientation of the image in the final rendering is controlled by\nthe *origin* and *extent* kwargs (and attributes on the resulting\n`~.AxesImage` instance) and the data limits of the axes.\n\nThe *extent* kwarg controls the bounding box in data coordinates that\nthe image will fill specified as ``(left, right, bottom, top)`` in\n**data coordinates**, the *origin* kwarg controls how the image fills\nthat bounding box, and the orientation in the final rendered image is\nalso affected by the axes limits.\n\n.. hint:: Most of the code below is used for adding labels and informative\n   text to the plots. The described effects of *origin* and *extent* can be\n   seen in the plots without the need to follow all code details.\n\n   For a quick understanding, you may want to skip the code details below and\n   directly continue with the discussion of the results.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\n\n\ndef index_to_coordinate(index, extent, origin):\n    \"\"\"Return the pixel center of an index.\"\"\"\n    left, right, bottom, top = extent\n\n    hshift = 0.5 * np.sign(right - left)\n    left, right = left + hshift, right - hshift\n    vshift = 0.5 * np.sign(top - bottom)\n    bottom, top = bottom + vshift, top - vshift\n\n    if origin == 'upper':\n        bottom, top = top, bottom\n\n    return {\n        \"[0, 0]\": (left, bottom),\n        \"[M', 0]\": (left, top),\n        \"[0, N']\": (right, bottom),\n        \"[M', N']\": (right, top),\n    }[index]\n\n\ndef get_index_label_pos(index, extent, origin, inverted_xindex):\n    \"\"\"\n    Return the desired position and horizontal alignment of an index label.\n    \"\"\"\n    if extent is None:\n        extent = lookup_extent(origin)\n    left, right, bottom, top = extent\n    x, y = index_to_coordinate(index, extent, origin)\n\n    is_x0 = index[-2:] == \"0]\"\n    halign = 'left' if is_x0 ^ inverted_xindex else 'right'\n    hshift = 0.5 * np.sign(left - right)\n    x += hshift * (1 if is_x0 else -1)\n    return x, y, halign\n\n\ndef get_color(index, data, cmap):\n    \"\"\"Return the data color of an index.\"\"\"\n    val = {\n        \"[0, 0]\": data[0, 0],\n        \"[0, N']\": data[0, -1],\n        \"[M', 0]\": data[-1, 0],\n        \"[M', N']\": data[-1, -1],\n    }[index]\n    return cmap(val / data.max())\n\n\ndef lookup_extent(origin):\n    \"\"\"Return extent for label positioning when not given explicitly.\"\"\"\n    if origin == 'lower':\n        return (-0.5, 6.5, -0.5, 5.5)\n    else:\n        return (-0.5, 6.5, 5.5, -0.5)\n\n\ndef set_extent_None_text(ax):\n    ax.text(3, 2.5, 'equals\\nextent=None', size='large',\n            ha='center', va='center', color='w')\n\n\ndef plot_imshow_with_labels(ax, data, extent, origin, xlim, ylim):\n    \"\"\"Actually run ``imshow()`` and add extent and index labels.\"\"\"\n    im = ax.imshow(data, origin=origin, extent=extent)\n\n    # extent labels (left, right, bottom, top)\n    left, right, bottom, top = im.get_extent()\n    if xlim is None or top > bottom:\n        upper_string, lower_string = 'top', 'bottom'\n    else:\n        upper_string, lower_string = 'bottom', 'top'\n    if ylim is None or left < right:\n        port_string, starboard_string = 'left', 'right'\n        inverted_xindex = False\n    else:\n        port_string, starboard_string = 'right', 'left'\n        inverted_xindex = True\n    bbox_kwargs = {'fc': 'w', 'alpha': .75, 'boxstyle': \"round4\"}\n    ann_kwargs = {'xycoords': 'axes fraction',\n                  'textcoords': 'offset points',\n                  'bbox': bbox_kwargs}\n    ax.annotate(upper_string, xy=(.5, 1), xytext=(0, -1),\n                ha='center', va='top', **ann_kwargs)\n    ax.annotate(lower_string, xy=(.5, 0), xytext=(0, 1),\n                ha='center', va='bottom', **ann_kwargs)\n    ax.annotate(port_string, xy=(0, .5), xytext=(1, 0),\n                ha='left', va='center', rotation=90,\n                **ann_kwargs)\n    ax.annotate(starboard_string, xy=(1, .5), xytext=(-1, 0),\n                ha='right', va='center', rotation=-90,\n                **ann_kwargs)\n    ax.set_title('origin: {origin}'.format(origin=origin))\n\n    # index labels\n    for index in [\"[0, 0]\", \"[0, N']\", \"[M', 0]\", \"[M', N']\"]:\n        tx, ty, halign = get_index_label_pos(index, extent, origin,\n                                             inverted_xindex)\n        facecolor = get_color(index, data, im.get_cmap())\n        ax.text(tx, ty, index, color='white', ha=halign, va='center',\n                bbox={'boxstyle': 'square', 'facecolor': facecolor})\n    if xlim:\n        ax.set_xlim(*xlim)\n    if ylim:\n        ax.set_ylim(*ylim)\n\n\ndef generate_imshow_demo_grid(extents, xlim=None, ylim=None):\n    N = len(extents)\n    fig = plt.figure(tight_layout=True)\n    fig.set_size_inches(6, N * (11.25) / 5)\n    gs = GridSpec(N, 5, figure=fig)\n\n    columns = {'label': [fig.add_subplot(gs[j, 0]) for j in range(N)],\n               'upper': [fig.add_subplot(gs[j, 1:3]) for j in range(N)],\n               'lower': [fig.add_subplot(gs[j, 3:5]) for j in range(N)]}\n    x, y = np.ogrid[0:6, 0:7]\n    data = x + y\n\n    for origin in ['upper', 'lower']:\n        for ax, extent in zip(columns[origin], extents):\n            plot_imshow_with_labels(ax, data, extent, origin, xlim, ylim)\n\n    for ax, extent in zip(columns['label'], extents):\n        text_kwargs = {'ha': 'right',\n                       'va': 'center',\n                       'xycoords': 'axes fraction',\n                       'xy': (1, .5)}\n        if extent is None:\n            ax.annotate('None', **text_kwargs)\n            ax.set_title('extent=')\n        else:\n            left, right, bottom, top = extent\n            text = ('left: {left:0.1f}\\nright: {right:0.1f}\\n' +\n                    'bottom: {bottom:0.1f}\\ntop: {top:0.1f}\\n').format(\n                        left=left, right=right, bottom=bottom, top=top)\n\n            ax.annotate(text, **text_kwargs)\n        ax.axis('off')\n    return columns"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Default extent\n--------------\n\nFirst, let's have a look at the default `extent=None`\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "generate_imshow_demo_grid(extents=[None])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Generally, for an array of shape (M, N), the first index runs along the\nvertical, the second index runs along the horizontal.\nThe pixel centers are at integer positions ranging from 0 to ``N' = N - 1``\nhorizontally and from 0 to ``M' = M - 1`` vertically.\n*origin* determines how to the data is filled in the bounding box.\n\nFor ``origin='lower'``:\n\n   - [0, 0] is at (left, bottom)\n   - [M', 0] is at (left, top)\n   - [0, N'] is at (right, bottom)\n   - [M', N'] is at (right, top)\n\n``origin='upper'`` reverses the vertical axes direction and filling:\n\n   - [0, 0] is at (left, top)\n   - [M', 0] is at (left, bottom)\n   - [0, N'] is at (right, top)\n   - [M', N'] is at (right, bottom)\n\nIn summary, the position of the [0, 0] index as well as the extent are\ninfluenced by *origin*:\n\n======  ===============  ==========================================\norigin  [0, 0] position  extent\n======  ===============  ==========================================\nupper   top left         ``(-0.5, numcols-0.5, numrows-0.5, -0.5)``\nlower   bottom left      ``(-0.5, numcols-0.5, -0.5, numrows-0.5)``\n======  ===============  ==========================================\n\nThe default value of *origin* is set by :rc:`image.origin` which defaults\nto ``'upper'`` to match the matrix indexing conventions in math and\ncomputer graphics image indexing conventions.\n\n\nExplicit extent\n---------------\n\nBy setting *extent* we define the coordinates of the image area. The\nunderlying image data is interpolated/resampled to fill that area.\n\nIf the axes is set to autoscale, then the view limits of the axes are set\nto match the *extent* which ensures that the coordinate set by\n``(left, bottom)`` is at the bottom left of the axes!  However, this\nmay invert the axis so they do not increase in the 'natural' direction.\n\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "extents = [(-0.5, 6.5, -0.5, 5.5),\n           (-0.5, 6.5, 5.5, -0.5),\n           (6.5, -0.5, -0.5, 5.5),\n           (6.5, -0.5, 5.5, -0.5)]\n\ncolumns = generate_imshow_demo_grid(extents)\nset_extent_None_text(columns['upper'][1])\nset_extent_None_text(columns['lower'][0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Explicit extent and axes limits\n-------------------------------\n\nIf we fix the axes limits by explicitly setting `set_xlim` / `set_ylim`, we\nforce a certain size and orientation of the axes.\nThis can decouple the 'left-right' and 'top-bottom' sense of the image from\nthe orientation on the screen.\n\nIn the example below we have chosen the limits slightly larger than the\nextent (note the white areas within the Axes).\n\nWhile we keep the extents as in the examples before, the coordinate (0, 0)\nis now explicitly put at the bottom left and values increase to up and to\nthe right (from the viewer point of view).\nWe can see that:\n\n- The coordinate ``(left, bottom)`` anchors the image which then fills the\n  box going towards the ``(right, top)`` point in data space.\n- The first column is always closest to the 'left'.\n- *origin* controls if the first row is closest to 'top' or 'bottom'.\n- The image may be inverted along either direction.\n- The 'left-right' and 'top-bottom' sense of the image may be uncoupled from\n  the orientation on the screen.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "generate_imshow_demo_grid(extents=[None] + extents,\n                          xlim=(-2, 8), ylim=(-1, 6))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
